package top.hmtools.HCHandle;

import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * httpclient中间工具
 * 
 * @author HyboJ
 *
 */
public class HttpClientHandleTools {

	private static Logger logger = LoggerFactory.getLogger(HttpClientHandleTools.class);

	/**
	 * HTTPclient连接池管理
	 */
	private static PoolingHttpClientConnectionManager phccm = null;
	
	/**
     * 从连接池中获取的httpclient
     */
    private static CloseableHttpClient hcPool = null;

	private static CloseableHttpClient hcSimple;

	/**
	 * 初始化
	 */
	public static void init() {
		init(20, 10);
	}

	/**
	 * 初始化
	 * 
	 * @param maxTotal
	 * @param defaultMaxPerRoute
	 */
	public static void init(int maxTotal, int defaultMaxPerRoute) {
		LayeredConnectionSocketFactory sslsf = null;
		try {
			sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
		} catch (NoSuchAlgorithmException e) {
			logger.error(e.getMessage(), e);
		}

		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
				.register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
		phccm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		phccm.setMaxTotal(maxTotal);
		phccm.setDefaultMaxPerRoute(defaultMaxPerRoute);
	}

	/**
	 * 获取连接池特性的httpclient
	 * @return
	 */
	public static CloseableHttpClient getPoolHttpClient() {
		if (phccm == null) {
			init(20, 10);
		}
		if (hcPool == null) {
			hcPool = HttpClients.custom().setConnectionManager(phccm).build();
		}
		return hcPool;
	}
	
	/**
	 * 获取非连接池特性的httpclient
	 * @return
	 */
	public static CloseableHttpClient getSimpleHttpClient() {
    	if(hcSimple == null){
    		hcSimple =  HttpClients.createDefault();//如果不采用连接池就是这种方式获取连接
    	}
       return hcSimple;
   }

}
